package tools.cookietools;

import lombok.NonNull;
import org.apache.http.cookie.ClientCookie;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.cookie.BasicClientCookie;
import tools.streamtools.NullableStream;

import java.util.Map;

import static java.util.Objects.nonNull;
import static java.util.stream.Collectors.toMap;
import static org.apache.http.cookie.ClientCookie.COMMENTURL_ATTR;
import static org.apache.http.cookie.ClientCookie.COMMENT_ATTR;
import static org.apache.http.cookie.ClientCookie.DISCARD_ATTR;
import static org.apache.http.cookie.ClientCookie.DOMAIN_ATTR;
import static org.apache.http.cookie.ClientCookie.EXPIRES_ATTR;
import static org.apache.http.cookie.ClientCookie.MAX_AGE_ATTR;
import static org.apache.http.cookie.ClientCookie.PATH_ATTR;
import static org.apache.http.cookie.ClientCookie.PORT_ATTR;
import static org.apache.http.cookie.ClientCookie.SECURE_ATTR;
import static org.apache.http.cookie.ClientCookie.VERSION_ATTR;


public class CookieUtils {
    public static BasicClientCookie toBasicClientCookie(@NonNull Cookie cookie) {
        if (cookie instanceof ReadOnlyCookie) {
            return ((ReadOnlyCookie) cookie).toBasicClientCookie();
        }
        BasicClientCookie basicClientCookie = new BasicClientCookie(cookie.getName(), cookie.getValue());
        basicClientCookie.setPath(cookie.getPath());
        basicClientCookie.setDomain(cookie.getDomain());
        basicClientCookie.setDomain(cookie.getDomain());
        basicClientCookie.setExpiryDate(cookie.getExpiryDate());
        basicClientCookie.setSecure(cookie.isSecure());
        basicClientCookie.setVersion(cookie.getVersion());
        if (cookie instanceof ClientCookie) {
            getAttributes((ClientCookie) cookie)
                .forEach(basicClientCookie::setAttribute);
        }
        return basicClientCookie;
    }

    private final static String[] attributeKeys = new String[]{
        "httponly", VERSION_ATTR, PATH_ATTR, DOMAIN_ATTR, MAX_AGE_ATTR, SECURE_ATTR, COMMENT_ATTR,
        EXPIRES_ATTR, PORT_ATTR, COMMENTURL_ATTR, DISCARD_ATTR
    };

    public static Map<String, String> getAttributes(ClientCookie cookie) {
        return NullableStream.of(attributeKeys)
            .filter(cookie::containsAttribute)
            .filter(k -> nonNull(cookie.getAttribute(k)))
            .collect(toMap(k -> k, cookie::getAttribute));
    }
}
